/*
 * Copyright (C) 2012 yueyueniao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hqw.mindanews.fragment;

import java.util.Date;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;

import com.hqw.mindanews.NewsDetailActivity;
import com.hqw.mindanews.R;
import com.hqw.mindanews.adapter.NewsAdapter;
import com.hqw.mindanews.bean.NewsMsg;
import com.hqw.mindanews.log.Log;
import com.hqw.mindanews.view.CustomProgressDialog;
import com.hqw.mindanews.view.XListView;
import com.hqw.mindanews.view.XListView.IXListViewListener;

public class NewFragment extends Fragment implements IXListViewListener {

	private XListView mListView;
	/**
	 * 是否第一次加载
	 */
	private boolean init;
	private List<NewsMsg> mNewsMsgsList;
	private NewsAdapter newsAdapter;
	// private ProgressDialog dialog;
	private int text;
	private CustomProgressDialog progressDialog = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Bundle args = getArguments();
		text = args != null ? Integer.parseInt(args.getString("text")) : 0;
		Log.i("bmob", text);
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		init = true;
		View view = inflater.inflate(R.layout.news_page, null);
		mListView = (XListView) view
				.findViewById(R.id.pull_to_refresh_xListView);

		mListView.setPullLoadEnable(true);// 是否允许加载更多
		mListView.setXListViewListener(this);
		return view;
	}

	public void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(getActivity());
		}

		progressDialog.show();
	}

	public void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onRefresh() {
		getservciesData();
	}

	@Override
	public void onLoadMore() {

	}

	/** 加载完毕 */
	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime(new Date().toString());
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		super.setUserVisibleHint(isVisibleToUser);
		// 是否可见
		if (isVisibleToUser) {
			Log.i("bmob", "加载");
			getdata();

		}
	}

	private void getdata() {
		if (init) {
			init = false;
			// 获取数据
			startProgressDialog();
			getservciesData();

		}

	}

	private void getservciesData() {
		// String Sql = "select * from NewsMsg";
		Log.i("bmob", "加载中");
		BmobQuery<NewsMsg> query = new BmobQuery<NewsMsg>();
		query.addWhereEqualTo("channel", text);
		query.order("-createdAt");
		query.include("user");
		query.setLimit(10);
		query.findObjects(getActivity(), new FindListener<NewsMsg>() {

			@Override
			public void onSuccess(List<NewsMsg> newsMsgs) {
				Log.i("bmob", "加载成功");
				if (newsMsgs.size() > 0) {
					String name = newsMsgs.get(0).getUser().getUsername();
					Log.i("bmob", "获取到的数据是" + name);
					// pb.clearAnimation();
					// dialog.hide();
					stopProgressDialog();
					setNewsAdapter(newsMsgs);
					onLoad();
				} else {
					Log.i("bmob", "获取到的数据长度是" + newsMsgs.size());
					stopProgressDialog();
					onLoad();
				}
			}

			@Override
			public void onError(int arg0, String arg1) {
				Log.i("bmob",arg0 +arg1);
				new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
                .setTitleText("Oops...")
                .setContentText("你麻痹，网络不给力啊!")
                .setCancelText("取消刷新")
                .setConfirmText("刷新！")
                .showCancelButton(true)
                .setCancelClickListener(new OnSweetClickListener() {
					
					@Override
					public void onClick(SweetAlertDialog sweetAlertDialog) {
						stopProgressDialog();
						
						
					}
				})
                .setConfirmClickListener(new OnSweetClickListener() {
					
					@Override
					public void onClick(SweetAlertDialog sweetAlertDialog) {
						getservciesData();
						
					}
				})
                .show();
			}
		});

	}

	protected void setNewsAdapter(List<NewsMsg> userNewsMsgs) {
		mNewsMsgsList = userNewsMsgs;
		newsAdapter = new NewsAdapter(getActivity(), userNewsMsgs);
		mListView.setHeaderDividersEnabled(false);
		mListView.setAdapter(newsAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override 
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
//				new SweetAlertDialog(getActivity()).setContentText(
//						"你点击了第" + position + "个item").show();
				
				Intent intent = new Intent(); 
				NewsMsg newsMsg = new NewsMsg();
				newsMsg = mNewsMsgsList.get(position-1);
                intent.putExtra("newsMsg", newsMsg);  
                intent.setClass(getActivity(), NewsDetailActivity.class);  
                startActivity(intent); 
				

			}
		});

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (getUserVisibleHint()) {
			getdata();
		}
	}

}
